package com.weixinadmin.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.weixindamin.exception.wxexception;

public class Token {
	private static Logger logger = Logger.getLogger(Token.class);//log4j
	
	private static String access_token;
	private static int expires_in;
	private static long taketime;
	private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
	private static String appid = "wx4ff785d7c23f08c6";					
	private static String secret = "6b0f857290a69391a100682c5c6b3db2";
	
	public Token(){
		if(null != access_token)
			return ;
	//	gettoken();
	}
	
	
	
	public String gettoken() throws wxexception{
		long nowtime =  System.currentTimeMillis();
		long time = nowtime - taketime;
		long expirestime = expires_in;
		expirestime = (expirestime - 10) * 1000;
		if((null == access_token)||(time > expirestime)){
			System.out.println( url+"&appid="+appid+"&secret"+secret);
			httpgettoken(url+"&appid="+appid+"&secret="+secret);
		}
		return access_token;
	}
	
	//static 方法不能访问 static 变量?
	//改注入方式
	
	public synchronized  String httpgettoken(String url) throws wxexception {
			 
		long nowtime =  System.currentTimeMillis();
		long time = nowtime - taketime;
		long expirestime = expires_in;
		expirestime = (expirestime - 10) * 1000;
		if((null != access_token)&&(time < expirestime)){
			return this.access_token;
		}
		String access_token = null;	
		HttpPool httppool = new HttpPool();			
		String httpresult = httppool.httpget(url);
		
		JSONObject json = JSONObject.fromObject(httpresult);
		try{
			access_token = json.getString("access_token");
			int expires_in = json.getInt("expires_in");
			this.access_token = access_token;
			this.expires_in = expires_in;
			this.taketime = nowtime;
			//return access_token;
		}catch (Exception e) {
			e.printStackTrace();	  
		} finally {
			return access_token;
		}
	 }
		
	 public static void main(String[] args) throws  IOException  
	 {  
	 
	 }
	 
}
